﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.Xml;
using WLMCoreLibrary;
using MiWebSite_Core;
using System.IO;

namespace MWS_AddDirectory.MisAnuncios
{
    public partial class Default : System.Web.UI.Page
    {
        public dbConnector ConexionDB;
        public WebSiteMainConfiguration config;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Request.QueryString["XMLLista"] != null)
            {
                config = WebSiteMainConfiguration.GetConfig();
                    ConexionDB = new dbConnector(config.Connections["WebSite"].value);
                    Cliente cliente = new Cliente(CurrentClient.Id, ref ConexionDB);
                    if (cliente.id != 0)
                    {
                        CargarListaAnuncios(cliente);
                        ConexionDB.CloseConnection();
                        Response.End();
                    }
                    else
                    {
                        ErrorObject error = new ErrorObject(ErrorCode.UserNotLogged, "Usuario No Logeado");
                        Response.ContentType = "text/xml";
                        Response.Write(WLMFunctions.SerializeObject(error, true));
                        Response.End();
                    }
            }
            if (Request.QueryString["original"] != null)
            {
                if (CurrentClient.Id != 0)
                {
                    
                }
                else
                {
                    //labelListadoAnuncios.Text = "<script>$('#PanelLogin').load('/MisAnuncios/login.aspx?original=true')</script>";
                }
            }
            else
            {
                if (Request.QueryString["xml"] != null)
                {
                    GenerarXML();
                }
                else
                {
                    TransformarXML();
                }
            }

        }

        protected void GenerarXML()
        {
            config = WebSiteMainConfiguration.GetConfig();
            ConexionDB = new dbConnector(config.Connections["WebSite"].value);
            MiWebSitePage pagina = new MiWebSitePage(ref ConexionDB);

            pagina.Title = "Directorio de " + DeCurrentDomain.Ciudad;
            pagina.DomainName = DeCurrentDomain.DomainName;
            pagina.DomainID = DeCurrentDomain.IdentificadorDominio;
            pagina.Scripts.Add("/jquery/scripts/AdminAnunciosCliente.js");
            XmlDocument xml = new XmlDocument();
            ConexionDB.CloseConnection();
            string urlpage = "http://" + DeCurrentDomain.SubDomain + "." + DeCurrentDomain.DomainName + "/MisAnuncios/?original=true";
            
            xml.LoadXml("<MiWebSiteContent><Contenido><![CDATA["+MiWebSiteFunctions.RenderControl(PanelUsuarioPanel)+" ]]></Contenido></MiWebSiteContent>");
            pagina.Contenido = xml;
            Response.ContentType = "text/xml";
            Response.Write(WLMFunctions.SerializeObject(pagina, true));
            Response.End();
        }

        protected void TransformarXML()
        {
            config = WebSiteMainConfiguration.GetConfig();
            List<ParametroTransformacionXML> parametros = FuncionesDirectorio.GetTransformationParameters();
            
            if (DeCurrentDomain.SubDomain != "www")
            {
                config = WebSiteMainConfiguration.GetConfig();
                ConexionDB = new dbConnector(config.Connections["WebSite"].value);
                parametros.Add(new ParametroTransformacionXML("subDomainSystemName", new Categoria(DeCurrentDomain.SubDomain, true, ref ConexionDB).nombreCategoria));
                ConexionDB.CloseConnection();
            }

            string urlPageXML = "http://" + DeCurrentDomain.SubDomain + "." + DeCurrentDomain.DomainName + "/misanuncios/?xml=true";
            string HTMLPagina = WLMFunctions.TransformXML(urlPageXML, config.Settings["siteURL"].value + config.Settings["skinPath"].value + "index.xsl", parametros);


            Response.Write(HTMLPagina);
            Response.End();
        }

        private void CargarListaAnuncios(Cliente cliente)
        {

            string FieldList = "SELECT A.id,nombre,C.NombreCategoria,mostrados,pagadoHasta,CONCAT('http://www."+CurrentDomain.DomainName+"/',A.id,'/',url,'/editar') FROM ANUNCIO A LEFT JOIN DIRECTORIOCAT2DIR C2A ON C2A.idDir=A.id LEFT JOIN DIRECTORIOCATS C ON C.id=C2A.idCat ";

            string where = "";
            if (Request["_search"] != null)
            {
                if (Request["_search"] == "true")
                {
                    XmlDocument filtrosBusqueda = Newtonsoft.Json.JsonConvert.DeserializeXmlNode("{'var':" + Request.QueryString["filters"] + "}");
                    where = " WHERE activo=1 AND idCliente='"+CurrentClient.Id+"' ";
                    foreach (XmlNode filtro in filtrosBusqueda.GetElementsByTagName("rules"))
                    {
                        string searchField = filtro.FirstChild.InnerText;
                        string searchToken = filtro.LastChild.InnerText;
                        switch (searchField)
                        {
                            case "id":
                                where += " AND id =" + searchToken + " ";
                                break;
                            //case "vendedorasignado":
                            //    where += " AND (V.Nombre LIKE '%" + searchToken + "%' OR V.Apellidos LIKE '%" + searchToken + "%') ";
                            //    break;
                            ////Buscando en Moneda y numeros
                            //case "SaldoActual":
                            //case "LimiteCredito":
                            //    where += " AND " + searchField + "=" + Convert.ToDecimal(searchToken.Replace("$", "").Replace(",", "")) + " ";
                            //    break;
                            ////Busqueda por cadena normal
                            default:
                                where += " AND " + searchField + " LIKE '%" + searchToken + "%'";
                                break;
                        }
                    }
                }
                else where = " WHERE activo=1  AND idCliente='" + CurrentClient.Id + "'";
            }
            where += "GROUP By A.id ";

            PaginacionXML paginacion = WLMFunctions.GetPaginacionXML();
            WLMFunctions.XMLGrid(FieldList,
                where,
                paginacion.SortOrder,
                paginacion.Limit,
                paginacion.DataPage,
                paginacion.RowsPerPage,
                true, true,ConexionDB);

        }


    }
}